// 初始化莫凡工具类
import utilConfig from './config/index';
import cloud from './cloud/index';

class mfutil {
  constructor(options) {
    options = options || {};
    this.config = new utilConfig(options.config).config;
    this.launchErrPage = this.launchErrPage;
    this.authorizeState = false;
    Date.prototype.format = function (fmt) {
      var o = {
        "M+": this.getMonth() + 1,                 //月份
        "d+": this.getDate(),                    //日
        "h+": this.getHours(),                   //小时
        "m+": this.getMinutes(),                 //分
        "s+": this.getSeconds(),                 //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
      };
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
      }
      for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
      }
      return fmt;
    }
  }
  // 初始化
  init(options) {
    options = options || {};
    if (!options.cloud || !options.emitter) {
      throw new Error('cloud or emitter need!');
    }
    // 初始化云函数的方法
    this.cloud = new cloud({ cloud: options.cloud, that: this });
    return new Promise(async resolve => {
      await this._initAllModule(this.cloud, options.emitter);
      // 根据配置文件调用授权
      if (this.config.autoOauth) {
        this.authorize();
      }
      resolve();
    });
  }

  // 初始化所有的模块
  async _initAllModule(_cloud, _emitter) {
    for (let i = 0; i < this.config.package.length; i++) {
      let util;
      try {
        let options = Object.assign({
          _cloud,
          _emitter,
          _that: this,
        }, this.config.package[i].parameter);
        util = new this.config.package[i].package(options);
      } catch (err) {
        console.log('模块初始化异常:', JSON.stringify(err));
      } finally {
        this[this.config.package[i].key] = util;
      }
    }
  }

  // 授权操作
  authorize(callback) {
    if (my && my.authorize) {
      my.authorize({
        scopes: 'scope.userInfo',
        success: res => {
          this.authorizeState = true;
        },
        fail: res => {
          // my.exit();
          // console.log(`-------授权失败------`, res);
          this.authorizeState = false;
        },
        complete: (res) => {
          this._onAuthorizate();
          if (this.authorizeState) {
            if (callback) callback(res);
          } else {
            if (this.config.oauthErrPage) {
              // console.log(`--------complete--0--------`, this.config.oauthErrPage)
              // this.launchErrPage(53001);
            } else if (this.config.oauthErrExit) {
              /**
               * @跳转到授权失败页面
               */
              this.launchErrPage('authorizationFail');

              /**
               * @直接跳转到设置页
               */
              /* my.showLoading({
                content: '权限检测中...',
                delay: 0,
                mask: true,
              });
              setTimeout(() => {
                my.getSetting({
                  complete: res => {
                    my.hideLoading();
                    if (res && res.authSetting && res.authSetting.userInfo) {
                      // 判断判断已经授权
                      my.reLaunch({
                        url: '/pages/index/index'
                      });
                    } else {
                      my.openSetting();
                    }
                  }
                });
              }, 500); */

              try {
                // my.exit();
                // console.log(`--------complete--2----`, `退出授权`)

              } catch (error) {
                // mfutil.launchErrPage(53001)
                console.log(error, '================error')
              }
            } else {
              if (callback) callback();
            }
          }
        }
      });
    }
  }

  // 授权完成
  _onAuthorizate() {
    for (let i = 0; i < this.config.package.length; i++) {
      if (this[this.config.package[i].key] && this[this.config.package[i].key].onAuthorizate) {
        this[this.config.package[i].key].onAuthorizate(this.authorizeState);
      }
    }
  }

  // 跳转到错误页面
  launchErrPage(code) {
    if (code == 'authorizationFail') {
      my.navigateTo({
        url: `/pages/error/error?code=${code}`
      });
    } else {
      my.reLaunch({
        url: `/pages/error/error?code=${code}`
      });
    }
  }

  // app.js onLaunch 当应用初始化完成时触发，全局只触发一次
  onLaunch(options) {
    for (let i = 0; i < this.config.package.length; i++) {
      if (this[this.config.package[i].key] && this[this.config.package[i].key].onLaunch) {
        this[this.config.package[i].key].onLaunch(options);
      }
    }
  }

  // app.js onShow 从后台被 scheme 重新打开
  onShow(options) {
    for (let i = 0; i < this.config.package.length; i++) {
      if (this[this.config.package[i].key] && this[this.config.package[i].key].onShow) {
        this[this.config.package[i].key].onShow(options);
      }
    }
  }

  // app.js onHide 当应用从前台进入后台时触发
  onHide() {
    for (let i = 0; i < this.config.package.length; i++) {
      if (this[this.config.package[i].key] && this[this.config.package[i].key].onHide) {
        this[this.config.package[i].key].onHide();
      }
    }
  }

  // 页面 onLoad 页面开始加载
  onLoad(query) {

    for (let i = 0; i < this.config.package.length; i++) {
      if (this[this.config.package[i].key] && this[this.config.package[i].key].onLoad) {
        this[this.config.package[i].key].onLoad(query);
      }
    }

  }

  // 页面 onReady 页面加载完成
  onReady() {
    for (let i = 0; i < this.config.package.length; i++) {
      if (this[this.config.package[i].key] && this[this.config.package[i].key].onReady) {
        this[this.config[i].key].onReady();
      }
    }
  }
}

export default mfutil;